package com.thread;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @author: mayu
 * @date: 2021年04月09日 11:36
 */
public class TestCountDownLatch {
    //volatile List lists = new ArrayList<>();
    volatile List lists = Collections.synchronizedList(new ArrayList<>());

    void add(Object o) {
        lists.add(o);
    }

    int size() {
        return lists.size();
    }

    public static void main(String[] args) {
        TestCountDownLatch tcdl = new TestCountDownLatch();

        CountDownLatch latch = new CountDownLatch(1);

        //t2相当于监视线程
        new Thread(() -> {
            System.out.println("t2启动");
            if (tcdl.lists.size() != 5) {
                try {
                    latch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("t2结束");
        }, "t2").start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            System.out.println("t1启动");
            for (int i = 0; i < 10; i++) {
                tcdl.add(i);
                System.out.println(i);
                if (tcdl.lists.size() == 5) {
                    latch.countDown();
                }
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("t1结束");
        }, "t1").start();

    }
}
